package com.zheng.api.server.service.base.um;

import com.alibaba.fastjson.JSONObject;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.server.service.command.MachineBusinessCommandInterface;
import com.zheng.api.server.service.command.WechatBusiness4CommandInterface;
import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.dao.model.*;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaConsumptionService;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaDepositService;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaRechargeService;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaTimecardService;
import com.zheng.common.constant.Constant;
import com.zheng.common.constant.PayConstant;
import com.zheng.common.util.*;
import com.zheng.pay.dao.model.PayMchInfo;
import com.zheng.pay.dao.model.PayMchInfoExample;
import com.zheng.pay.rpc.api.PayMchInfoService;
import com.zheng.umbrella.common.constant.UmbrellaConstant;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.rpc.api.*;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import com.zheng.wechat.mp.dao.model.*;
import com.zheng.wechat.mp.rpc.api.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: lvb
 * @date: 17/9/9
 * @description:
 */
@Service
public class Base4UmbrellaService{

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Base4UmbrellaService.class);
    @Autowired
    UmbrellaHardwareMachineService umbrellaHardwareMachineService;
    @Autowired
    UmbrellaHardwarePathService umbrellaHardwarePathService;
    @Autowired
    UmbrellaHardwareUmbrellaService umbrellaHardwareUmbrellaService;
    @Autowired
    UmbrellaRuleRentService umbrellaRuleRentService;
    @Autowired
    UmbrellaRuleDepositService umbrellaRuleDepositService;
    @Autowired
    UmbrellaRuleTimecardService umbrellaRuleTimecardService;
    @Autowired
    WechatMpGzuserService wechatMpGzuserService;
    @Autowired
    WechatMpSystemAccountService wechatMpSystemAccountService;
    @Autowired
    BusinessOrderUmbrellaConsumptionService businessOrderUmbrellaConsumptionService;
    @Autowired
    BusinessOrderUmbrellaRechargeService businessOrderUmbrellaRechargeService;
    @Autowired
    BusinessOrderUmbrellaDepositService businessOrderUmbrellaDepositService;
    @Autowired
    BusinessOrderUmbrellaTimecardService businessOrderUmbrellaTimecardService;
    @Autowired
    UpmsSystemParamService upmsSystemParamService;
    @Autowired
    UmbrellaHardwareMqttcommandLogService umbrellaHardwareMqttcommandLogService;
    @Autowired
    private PayMchInfoService payMchInfoService;
    @Autowired
    private WechatMpWebJwidService wechatMpWebJwidService;
    @Autowired
    UmbrellaRuleSpecialconfigDetailService umbrellaRuleSpecialconfigDetailService;
    @Autowired
    WechatMpWxappfrommessageService wechatMpWxappfrommessageService;
    @Autowired
    WechatMpWxapptempletecfgService wechatMpWxapptempletecfgService;
    //商户ID
    @Value("${pay.paycenter.mchId}")
    private String mchId ;


    /**
     * 获取伞机业务处理工厂
     * @param machineCode
     * @return
     */
    public MachineBusinessCommandInterface baseMachineBusinessCommandFactory(String machineCode){
        MachineBusinessCommandInterface machineBusinessCommandInterface = null;
        try {
            UmbrellaHardwareMachine umbrellaHardwareMachine = baseSelectUmbrellaHardwareMachineCache(machineCode);
            if (umbrellaHardwareMachine != null) {
                int type = umbrellaHardwareMachine.getType();
                String serviceName = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_TYPE_SERVICE_V" + type);
                machineBusinessCommandInterface = (MachineBusinessCommandInterface) SpringContextUtil.getBean(serviceName);
            }
        }catch (Exception e){
            LOGGER.error( "获取伞机业务处理工厂，伞机编码:" + machineCode,e);
        }
        if(machineBusinessCommandInterface == null){
            machineBusinessCommandInterface = (MachineBusinessCommandInterface) SpringContextUtil.getBean("machineBusiness4CommandServiceV1");
        }
       return machineBusinessCommandInterface;
    }
    /**
     * 获取小程序业务处理工厂
     * @param machineCode
     * @return
     */
    public WechatBusiness4CommandInterface baseWechatBusinessCommandFactory(String machineCode){
        WechatBusiness4CommandInterface wechatBusiness4CommandInterface = null;
        try {
            UmbrellaHardwareMachine umbrellaHardwareMachine = baseSelectUmbrellaHardwareMachineCache(machineCode);
            if (umbrellaHardwareMachine != null) {
                int type = umbrellaHardwareMachine.getType();
                String serviceName = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_WECHAT_TYPE_SERVICE_V" + type);
                wechatBusiness4CommandInterface = (WechatBusiness4CommandInterface) SpringContextUtil.getBean(serviceName);
            }
        }catch (Exception e){
            LOGGER.error( "获取伞机业务处理工厂，伞机编码:" + machineCode,e);
        }
        if(wechatBusiness4CommandInterface == null){
            wechatBusiness4CommandInterface = (WechatBusiness4CommandInterface) SpringContextUtil.getBean("wechatBusiness4CommandServiceV1");
        }
        return wechatBusiness4CommandInterface;
    }
    /**
     * 根据伞机编码、在线状态查询伞机
     * @param machineCode
     * @param isInUse
     * @return
     */
    public UmbrellaHardwareMachine baseSelectUmbrellaHardwareMachineByStatus(String machineCode,boolean isOnline){
        UmbrellaHardwareMachineExample queryExample = new UmbrellaHardwareMachineExample();
        UmbrellaHardwareMachineExample.Criteria queryCriteria = queryExample.createCriteria();
        //未删除
        queryCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if(isOnline){
            //在线状态
            queryCriteria.andStatusEqualTo(ApiConstant.UM_MACHINE_STATUS_UP);
        }
        //机器编码
        queryCriteria.andCodeEqualTo(machineCode);
        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectFirstByExample(queryExample);
        return umbrellaHardwareMachine;
    }
    /**
     * 根据伞机编码查询伞机(缓存)
     * @param machineCode
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectUmbrellaHardwareMachineCache_'+#machineCode")
    public UmbrellaHardwareMachine baseSelectUmbrellaHardwareMachineCache(String machineCode){
        UmbrellaHardwareMachineExample queryExample = new UmbrellaHardwareMachineExample();
        UmbrellaHardwareMachineExample.Criteria queryCriteria = queryExample.createCriteria();
        //未删除
        queryCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //机器编码
        queryCriteria.andCodeEqualTo(machineCode);
        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectFirstByExample(queryExample);
        return umbrellaHardwareMachine;
    }
    /**
     * 根据伞机编码查询伞机(非缓存)
     * @param machineCode
     * @return
     */
    public UmbrellaHardwareMachine baseSelectUmbrellaHardwareMachineNoCache(String machineCode){
        UmbrellaHardwareMachineExample queryExample = new UmbrellaHardwareMachineExample();
        UmbrellaHardwareMachineExample.Criteria queryCriteria = queryExample.createCriteria();
        //未删除
        queryCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //机器编码
        queryCriteria.andCodeEqualTo(machineCode);
        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectFirstByExample(queryExample);
        return umbrellaHardwareMachine;
    }

    /**
     * 根据条件查询伞机
     * @param queryExample
     * @return
     */
    public UmbrellaHardwareMachine baseSelectUmbrellaHardwareMachineByExample(UmbrellaHardwareMachineExample queryExample){
        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectFirstByExample(queryExample);
        return umbrellaHardwareMachine;
    }
    /**
     * 查询所有有效伞机
     * @return
     */
    public List<UmbrellaHardwareMachine> baseSelectAllUmbrellaHardwareMachine(){
        UmbrellaHardwareMachineExample queryExample = new UmbrellaHardwareMachineExample();
        UmbrellaHardwareMachineExample.Criteria queryCriteria = queryExample.createCriteria();
        //未删除
        queryCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        List<UmbrellaHardwareMachine> machineList = umbrellaHardwareMachineService.selectByExample(queryExample);
        return machineList;
    }
    /**
     * 根据状态查询所有有效伞机
     * @return
     */
    public List<UmbrellaHardwareMachine> baseSelectUmbrellaHardwareMachineListByStatus(ArrayList<Integer> statusList){
        UmbrellaHardwareMachineExample queryExample = new UmbrellaHardwareMachineExample();
        UmbrellaHardwareMachineExample.Criteria queryCriteria = queryExample.createCriteria();
        //未删除
        queryCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        queryCriteria.andStatusIn(statusList);
        List<UmbrellaHardwareMachine> machineList = umbrellaHardwareMachineService.selectByExample(queryExample);
        return machineList;
    }
    /**
     * 根据伞机编码、伞道编码查询伞道(缓存)
     * @param machineCode
     * @param pathCode
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectUmbrellaHardwarePathCache_'+#machineCode+'_'+#pathCode")
    public UmbrellaHardwarePath baseSelectUmbrellaHardwarePathCache(String machineCode,String pathCode){
        UmbrellaHardwarePathExample queryExample = new UmbrellaHardwarePathExample();
        queryExample.createCriteria().andMachineCodeEqualTo(machineCode).andCodeEqualTo(pathCode).andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        UmbrellaHardwarePath umbrellaHardwarePath = umbrellaHardwarePathService.selectFirstByExample(queryExample);
        return umbrellaHardwarePath;
    }
    /**
     * 根据伞机编码、伞道编码查询伞道(非缓存)
     * @param machineCode
     * @param pathCode
     * @return
     */
    public UmbrellaHardwarePath baseSelectUmbrellaHardwarePathNoCache(String machineCode,String pathCode){
        UmbrellaHardwarePathExample queryExample = new UmbrellaHardwarePathExample();
        queryExample.createCriteria().andMachineCodeEqualTo(machineCode).andCodeEqualTo(pathCode).andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        UmbrellaHardwarePath umbrellaHardwarePath = umbrellaHardwarePathService.selectFirstByExample(queryExample);
        return umbrellaHardwarePath;
    }
    /**
     * 根据伞机编码查询第一条伞道(缓存)
     * @param machineCode
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectFirstUmbrellaHardwarePathCache_'+#machineCode")
    public UmbrellaHardwarePath baseSelectFirstUmbrellaHardwarePathCache(String machineCode){
        UmbrellaHardwarePathExample queryExample = new UmbrellaHardwarePathExample();
        queryExample.createCriteria().andMachineCodeEqualTo(machineCode).andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        UmbrellaHardwarePath umbrellaHardwarePath = umbrellaHardwarePathService.selectFirstByExample(queryExample);
        return umbrellaHardwarePath;
    }
    /**
     * 根据伞机编码查询第一条伞道(非缓存)
     * @param machineCode
     * @return
     */
    public UmbrellaHardwarePath baseSelectFirstUmbrellaHardwarePathNoCache(String machineCode){
        UmbrellaHardwarePathExample queryExample = new UmbrellaHardwarePathExample();
        queryExample.createCriteria().andMachineCodeEqualTo(machineCode).andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        UmbrellaHardwarePath umbrellaHardwarePath = umbrellaHardwarePathService.selectFirstByExample(queryExample);
        return umbrellaHardwarePath;
    }
    /**
     * 根据雨伞芯片ID查询雨伞(缓存)
     * @param chipNumber
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectUmbrellaHardwareUmbrellaCache_'+#chipNumber")
    public UmbrellaHardwareUmbrella baseSelectUmbrellaHardwareUmbrellaCache(String chipNumber){
        if(StringUtils.isEmpty(chipNumber)){
            return null;
        }
        UmbrellaHardwareUmbrellaExample umbrellaExample = new UmbrellaHardwareUmbrellaExample();
        UmbrellaHardwareUmbrellaExample.Criteria umbrellaCriteria = umbrellaExample.createCriteria();
        //未删除
        umbrellaCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //雨伞芯片id
        umbrellaCriteria.andChipNumberEqualTo(chipNumber);
        UmbrellaHardwareUmbrella umbrellaHardwareUmbrella = umbrellaHardwareUmbrellaService.selectFirstByExample(umbrellaExample);
        return umbrellaHardwareUmbrella;
    }
    /**
     * 根据雨伞芯片ID查询雨伞(非缓存)
     * @param chipNumber
     * @return
     */
    public UmbrellaHardwareUmbrella baseSelectUmbrellaHardwareUmbrellaNoCache(String chipNumber){
        if(StringUtils.isEmpty(chipNumber)){
            return null;
        }
        UmbrellaHardwareUmbrellaExample umbrellaExample = new UmbrellaHardwareUmbrellaExample();
        UmbrellaHardwareUmbrellaExample.Criteria umbrellaCriteria = umbrellaExample.createCriteria();
        //未删除
        umbrellaCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //雨伞芯片id
        umbrellaCriteria.andChipNumberEqualTo(chipNumber);
        UmbrellaHardwareUmbrella umbrellaHardwareUmbrella = umbrellaHardwareUmbrellaService.selectFirstByExample(umbrellaExample);
        return umbrellaHardwareUmbrella;
    }
    /**
     * 根据规则ID查询租金规则(非缓存)
     * @param ruleId
     * @param isInUse
     * @return
     */
    public UmbrellaRuleRent baseSelectUmbrellaRuleRentNoCache(Integer ruleId, boolean isInUse){
        UmbrellaRuleRentExample umbrellaExample = new UmbrellaRuleRentExample();
        UmbrellaRuleRentExample.Criteria umbrellaCriteria = umbrellaExample.createCriteria();
        //未删除
        umbrellaCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //状态正常
        if(isInUse) {
            umbrellaCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
        }
        umbrellaCriteria.andIdEqualTo(ruleId);
        UmbrellaRuleRent umbrellaRuleRent = umbrellaRuleRentService.selectFirstByExample(umbrellaExample);
        return umbrellaRuleRent;
    }
    /**
     * 根据规则ID查询租金规则(缓存)
     * @param ruleId
     * @param isInUse
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectUmbrellaRuleRentCache_'+#ruleId")
    public UmbrellaRuleRent baseSelectUmbrellaRuleRentCache(Integer ruleId, boolean isInUse){
        UmbrellaRuleRentExample umbrellaExample = new UmbrellaRuleRentExample();
        UmbrellaRuleRentExample.Criteria umbrellaCriteria = umbrellaExample.createCriteria();
        //未删除
        umbrellaCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //状态正常
        if(isInUse) {
            umbrellaCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
        }
        umbrellaCriteria.andIdEqualTo(ruleId);
        UmbrellaRuleRent umbrellaRuleRent = umbrellaRuleRentService.selectFirstByExample(umbrellaExample);
        return umbrellaRuleRent;
    }
    /**
     * 根据规则ID查询预付金规则(缓存)
     * @param ruleId
     * @param isInUse
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectUmbrellaRuleDepositCache_'+#ruleId")
    public UmbrellaRuleDeposit baseSelectUmbrellaRuleDepositCache(Integer ruleId, boolean isInUse){
        UmbrellaRuleDepositExample umbrellaExample = new UmbrellaRuleDepositExample();
        UmbrellaRuleDepositExample.Criteria umbrellaCriteria = umbrellaExample.createCriteria();
        //未删除
        umbrellaCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //状态正常
        if(isInUse) {
            umbrellaCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
            long nowtime = new Date().getTime();
            umbrellaCriteria.andBeginTimeLessThanOrEqualTo(nowtime);
            umbrellaCriteria.andEndTimeGreaterThanOrEqualTo(nowtime);
        }
        umbrellaCriteria.andIdEqualTo(ruleId);
        UmbrellaRuleDeposit umbrellaRuleDeposit = umbrellaRuleDepositService.selectFirstByExample(umbrellaExample);
        return umbrellaRuleDeposit;
    }
    /**
     * 根据规则ID查询预付金规则(非缓存)
     * @param ruleId
     * @param isInUse
     * @return
     */
    public UmbrellaRuleDeposit baseSelectUmbrellaRuleDepositNoCache(Integer ruleId, boolean isInUse){
        UmbrellaRuleDepositExample umbrellaExample = new UmbrellaRuleDepositExample();
        UmbrellaRuleDepositExample.Criteria umbrellaCriteria = umbrellaExample.createCriteria();
        //未删除
        umbrellaCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //状态正常
        if(isInUse) {
            umbrellaCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
            long nowtime = new Date().getTime();
            umbrellaCriteria.andBeginTimeLessThanOrEqualTo(nowtime);
            umbrellaCriteria.andEndTimeGreaterThanOrEqualTo(nowtime);
        }
        umbrellaCriteria.andIdEqualTo(ruleId);
        UmbrellaRuleDeposit umbrellaRuleDeposit = umbrellaRuleDepositService.selectFirstByExample(umbrellaExample);
        return umbrellaRuleDeposit;
    }
    /**
     * 根据规则ID查询时长卡规则(缓存)
     * @param ruleId
     * @param isInUse
     * @return
     */
    @Cacheable(value="zheng-api-server-service-ehcache",key="'baseSelectUmbrellaRuleTimecardCache_'+#ruleId")
    public UmbrellaRuleTimecard baseSelectUmbrellaRuleTimecardCache(Integer ruleId, boolean isInUse){
        UmbrellaRuleTimecardExample timecardExample = new UmbrellaRuleTimecardExample();
        UmbrellaRuleTimecardExample.Criteria timecardCriteria = timecardExample.createCriteria();
        //未删除
        timecardCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //状态正常
        if(isInUse) {
            timecardCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
            long nowtime = new Date().getTime();
            timecardCriteria.andBeginTimeLessThanOrEqualTo(nowtime);
            timecardCriteria.andEndTimeGreaterThanOrEqualTo(nowtime);
        }
        timecardCriteria.andIdEqualTo(ruleId);
        UmbrellaRuleTimecard umbrellaRuleTimecard = umbrellaRuleTimecardService.selectFirstByExample(timecardExample);
        return umbrellaRuleTimecard;
    }
    /**
     * 根据规则ID查询时长卡规则(非缓存)
     * @param ruleId
     * @param isInUse
     * @return
     */
    public UmbrellaRuleTimecard baseSelectUmbrellaRuleTimecardNoCache(Integer ruleId, boolean isInUse){
        UmbrellaRuleTimecardExample timecardExample = new UmbrellaRuleTimecardExample();
        UmbrellaRuleTimecardExample.Criteria timecardCriteria = timecardExample.createCriteria();
        //未删除
        timecardCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        //状态正常
        if(isInUse) {
            timecardCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
            long nowtime = new Date().getTime();
            timecardCriteria.andBeginTimeLessThanOrEqualTo(nowtime);
            timecardCriteria.andEndTimeGreaterThanOrEqualTo(nowtime);
        }
        timecardCriteria.andIdEqualTo(ruleId);
        UmbrellaRuleTimecard umbrellaRuleTimecard = umbrellaRuleTimecardService.selectFirstByExample(timecardExample);
        return umbrellaRuleTimecard;
    }

    /**
     * 根据用户和代理查询用户已购买的有效时长卡(非缓存)
     * @param userId
     * @param agentId
     * @param isDifference
     * @return
     */
    public BusinessOrderUmbrellaTimecard baseSelectLastBusinessOrderUmbrellaTimecardNoCache(Integer userId, Integer agentId,boolean isDifference){
        Date nowDate = DateUtil.getDate();
        BusinessOrderUmbrellaTimecardExample example = new BusinessOrderUmbrellaTimecardExample();
        BusinessOrderUmbrellaTimecardExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userId);
        if(isDifference) {
            if (agentId == null) {
                criteria.andAgentidIsNull();
            } else {
                criteria.andAgentidEqualTo(agentId);
            }
        }
        criteria.andStatusBetween(2,3);//  只展示支付成功、業務處理成功的数据
        example.setOrderByClause("CreateTime desc");
        BusinessOrderUmbrellaTimecard latestTimeCard =  businessOrderUmbrellaTimecardService.selectFirstByExample(example);
        return  latestTimeCard;
    }
    /**
     * 根据用户和代理查询用户已购买的首次时长卡(非缓存)
     * @param userId
     * @param agentId
     * @param isDifference
     * @return
     */
    public BusinessOrderUmbrellaTimecard baseSelectFirstBusinessOrderUmbrellaTimecardNoCache(Integer userId, Integer agentId,boolean isDifference){
        BusinessOrderUmbrellaTimecardExample example = new BusinessOrderUmbrellaTimecardExample();
        BusinessOrderUmbrellaTimecardExample.Criteria criteria = example.createCriteria();
        criteria.andUseridEqualTo(userId);
        if(isDifference) {
            if (agentId == null) {
                criteria.andAgentidIsNull();
            } else {
                criteria.andAgentidEqualTo(agentId);
            }
        }
        criteria.andStatusBetween(2,3);//  只展示支付成功、業務處理成功的数据
        example.setOrderByClause("CreateTime asc");
        BusinessOrderUmbrellaTimecard latestTimeCard =  businessOrderUmbrellaTimecardService.selectFirstByExample(example);
        return  latestTimeCard;
    }
    /**
     * 根据用户ID查询用户信息
     * @param userId
     * @param isInUse
     * @return
     */
    public WechatMpGzuser baseSelectWechatMpGzuser(Integer userId, boolean isInUse){
        WechatMpGzuserExample userExample = new WechatMpGzuserExample();
        WechatMpGzuserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andIdEqualTo(userId);
        if(isInUse) {
            //未删除
            userCriteria.andUserstatusEqualTo(Constant.CONST_FLAG_NORMAL);
        }
        WechatMpGzuser wechatMpGzuser = wechatMpGzuserService.selectFirstByExample(userExample);
        return wechatMpGzuser;
    }
    /**
     * 根据用户ID更新指定信息
     * @param wechatMpGzuser
     * @param userId
     * @return
     */
    public int updateWechatMpGzuserByPrimaryKeySelective(WechatMpGzuser wechatMpGzuser,Integer userId){
        wechatMpGzuser.setId(userId);
        int ret = wechatMpGzuserService.updateByPrimaryKeySelective(wechatMpGzuser);
        return ret;
    }
    /**
     * 根据用户ID查询用户账号
     * @param userId
     * @return
     */
    public WechatMpSystemAccount baseSelectWechatMpSystemAccont(Integer userId){
        WechatMpSystemAccountExample accountExample = new WechatMpSystemAccountExample();
        WechatMpSystemAccountExample.Criteria accountCriteria = accountExample.createCriteria();
        accountCriteria.andUserIdEqualTo(userId);
        WechatMpSystemAccount wechatMpSystemAccount = wechatMpSystemAccountService.selectFirstByExample(accountExample);
        return wechatMpSystemAccount;
    }

    /**
     * 按雨伞ID查询未归还订单
     * @param chipNumber
     * @return
     */
    public BusinessOrderUmbrellaConsumption baseSelectBusinessOrderUmbrellaUnReturnByChipNumber(String chipNumber,boolean isContainFail,String notThisOrderNo){
        BusinessOrderUmbrellaConsumptionExample consumptionExample= new BusinessOrderUmbrellaConsumptionExample();
        BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
        consumptionExample.setOrderByClause(" createtime desc"); //如果存在多條保證獲取最新的一條
        //chipNumber
        consumptionCriteria.andChipNumberEqualTo(chipNumber);
        if(isContainFail) {
            //雨伞订单状态，包括已借出和还伞失败
            consumptionCriteria.andStatusBetween(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3, BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
        }else{
            //雨伞订单状态，包括已借出
            consumptionCriteria.andStatusEqualTo(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3);
        }
        //非指定订单
        if(StringUtils.isNotEmpty(notThisOrderNo)){
            consumptionCriteria.andOrdernoNotEqualTo(notThisOrderNo);
        }
        BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = businessOrderUmbrellaConsumptionService.selectFirstByExample(consumptionExample);
        return businessOrderUmbrellaConsumption;
    }
    /**
     * 按用户账号查询未归还订单
     * @param userId
     * @return
     */
    public BusinessOrderUmbrellaConsumption baseSelectBusinessOrderUmbrellaUnReturnByAccount(Integer userId,boolean isContainFail){
        BusinessOrderUmbrellaConsumptionExample consumptionExample= new BusinessOrderUmbrellaConsumptionExample();
        // 需要排序，否则获取不是最新一条
        consumptionExample.setOrderByClause("CreateTime desc");

        BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
        //chipNumber
        consumptionCriteria.andUseridEqualTo(userId);
        if(isContainFail) {
            //雨伞订单状态，包括已借出和还伞失败
            consumptionCriteria.andStatusBetween(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3, BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
        }else{
            //雨伞订单状态，包括已借出
            consumptionCriteria.andStatusEqualTo(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3);
        }
        BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = businessOrderUmbrellaConsumptionService.selectFirstByExample(consumptionExample);
        return businessOrderUmbrellaConsumption;
    }

    /**
     * 按订单号查询借还伞订单
     * @param orderNo
     * @return
     */
    public BusinessOrderUmbrellaConsumption baseSelectBusinessOrderUmbrellaConsumptionByOrderNo(String orderNo){
        BusinessOrderUmbrellaConsumptionExample consumptionExample = new BusinessOrderUmbrellaConsumptionExample();
        BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
        consumptionCriteria.andOrdernoEqualTo(orderNo);
        BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = businessOrderUmbrellaConsumptionService.selectFirstByExample(consumptionExample);
        return businessOrderUmbrellaConsumption;
    }

    /**
     * 根据订单号查询用户充值订单
     * @param orderNo
     * @return
     */
    public BusinessOrderUmbrellaRecharge baseSelectBusinessOrderUmbrellaRecharge(String orderNo){
        BusinessOrderUmbrellaRechargeExample rechargeExample = new BusinessOrderUmbrellaRechargeExample();
        BusinessOrderUmbrellaRechargeExample.Criteria  rechargeCriteria = rechargeExample.createCriteria();
        rechargeCriteria.andOrdernoEqualTo(orderNo);
        BusinessOrderUmbrellaRecharge recharge = businessOrderUmbrellaRechargeService.selectFirstByExample(rechargeExample);;
        return recharge;
    }

    /**
     * 根据订单号查询用户预付金订单
     * @param orderNo
     * @return
     */
    public BusinessOrderUmbrellaDeposit baseSelectBusinessOrderUmbrellaDeposit(String orderNo){
       BusinessOrderUmbrellaDepositExample depositExample = new BusinessOrderUmbrellaDepositExample();
       BusinessOrderUmbrellaDepositExample.Criteria  depositCriteria = depositExample.createCriteria();
       depositCriteria.andOrdernoEqualTo(orderNo);
       BusinessOrderUmbrellaDeposit deposit = businessOrderUmbrellaDepositService.selectFirstByExample(depositExample);;
       return deposit;
    }
    /**
     * 根据订单号查询用户时长卡订单
     * @param orderNo
     * @return
     */
    public BusinessOrderUmbrellaTimecard baseSelectBusinessOrderUmbrellaTimecard(String orderNo){
        BusinessOrderUmbrellaTimecardExample timecardExample = new BusinessOrderUmbrellaTimecardExample();
        BusinessOrderUmbrellaTimecardExample.Criteria  timecardCriteria = timecardExample.createCriteria();
        timecardCriteria.andOrdernoEqualTo(orderNo);
        BusinessOrderUmbrellaTimecard timecardOrder = businessOrderUmbrellaTimecardService.selectFirstByExample(timecardExample);;
        return timecardOrder;
    }
    /**
     * 新增借还伞订单
     * @param insertConsumption
     * @return
     */
    public int insertBusinessOrderUmbrellaConsumption(BusinessOrderUmbrellaConsumption insertConsumption){
        return businessOrderUmbrellaConsumptionService.insert(insertConsumption);
    }
    /**
     * 根据条件更新伞机信息
     * @param updateMachine
     * @param example
     * @return
     */
    public int updateUmbrellaHardwareMachine(UmbrellaHardwareMachine updateMachine, UmbrellaHardwareMachineExample example){
       return umbrellaHardwareMachineService.updateByExampleSelective(updateMachine,example);
    }
    /**
     * 根据条件更新伞机伞道信息
     * @param updatePath
     * @param example
     * @return
     */
    public int updateUmbrellaHardwarePath(UmbrellaHardwarePath updatePath, UmbrellaHardwarePathExample example){
        return umbrellaHardwarePathService.updateByExampleSelective(updatePath,example);
    }
    /**
     * 根据条件更新借还伞订单
     * @param updateConsumption
     * @param example
     * @return
     */
    public int updateBusinessOrderUmbrellaConsumption(BusinessOrderUmbrellaConsumption updateConsumption, BusinessOrderUmbrellaConsumptionExample example){
        return businessOrderUmbrellaConsumptionService.updateByExampleSelective(updateConsumption,example);
    }
    /**
     * 根据条件更新借还伞订单
     * @param key
     * @return
     */
    public String querySystemParamValueByParam_key(String key){
        return upmsSystemParamService.querySystemParamValueByParam_key(key);
    }
    /**
     * 按封顶金额规则计算租金
     * @param cost
     * @param orderFeeLimit
     * @param rentFeeLimit
     * @param spFeeLimit
     * @param isFeeLimit
     * @return
     */
    public double calculateAmountByCapping(double rentFeeLimit, double spFeeLimit,Integer isFeeLimit){
        double realFeeAmount = 0;
        //判断封顶金额规则是否开启
        if(isFeeLimit!=null && isFeeLimit == Constant.CONST_ENABLE ){
            //租金规则配置的封顶金额大于0时，以租金规则配置的封顶金额为准，否则以个性规则配置的封顶金额为准；如果两者均配置为小于等于0，则按正常计费
            if(rentFeeLimit>0){
                realFeeAmount = rentFeeLimit;
            }else if(spFeeLimit >0){
                realFeeAmount = spFeeLimit;
            }
        }
        return realFeeAmount;
    }

    /**
     * 更新雨伞 归属设备及当前设备，代理
     * @param umbrellaNumber
     * @param agentId
     * @param machineCode
     */
    public void updateUmbrellaAgentAndMachine(List<String> umbrellaNumber,Integer agentId,String machineCode){
        if(umbrellaNumber.size() == 0)return;
        UmbrellaHardwareUmbrellaExample example = new UmbrellaHardwareUmbrellaExample();
        UmbrellaHardwareUmbrellaExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIn(umbrellaNumber);
        criteria.andMachineCodeIsNull();
        UmbrellaHardwareUmbrella umbrella = new UmbrellaHardwareUmbrella();
        umbrella.setAgentId(agentId);
        umbrella.setMachineCode(machineCode);
        umbrella.setCurrentMachineCode(machineCode);
        umbrellaHardwareUmbrellaService.updateByExampleSelective(umbrella,example);
    }

    /**
     * 更新硬件雨伞剩余量、伞道剩余量
     * @param machineCode
     * @param pathCode
     * @param pathNumber
     * @param count
     * @return
     */
    public void updateUmbrellaMachineAndPathRemainder(String machineCode,String pathCode,Integer pathNumber,Integer count){
        try {
            //更新伞机雨伞余量
            UmbrellaHardwareMachine machineInfo = this.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
            if(machineInfo!=null) {
                UmbrellaHardwareMachine updateMachine = new UmbrellaHardwareMachine();
                updateMachine.setRemainder(machineInfo.getRemainder() + count);
                UmbrellaHardwareMachineExample updateExample = new UmbrellaHardwareMachineExample();
                updateExample.createCriteria().andCodeEqualTo(machineCode).andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
                int ret = updateUmbrellaHardwareMachine(updateMachine, updateExample);
            }

            //更新伞道雨伞余量
            UmbrellaHardwarePath pathInfo = this.baseSelectUmbrellaHardwarePathNoCache(machineCode,pathCode);
            if(pathInfo==null){
                pathInfo = baseSelectFirstUmbrellaHardwarePathNoCache(machineCode);
            }
            if(pathInfo!=null) {
                UmbrellaHardwarePath updatePath = new UmbrellaHardwarePath();
                updatePath.setRemainder(pathInfo.getRemainder() + count);
                UmbrellaHardwarePathExample updatePathExample = new UmbrellaHardwarePathExample();
                updatePathExample.createCriteria().andMachineCodeEqualTo(machineCode).andCodeEqualTo(pathInfo.getCode()).andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
                int ret = updateUmbrellaHardwarePath(updatePath, updatePathExample);
            }
        }catch(Exception e){
            LOGGER.error("更新失败",e.getCause());
        }
    }
    /**
     * 更新雨伞状态
     * @param chipNumber
     * @param status
     * @return
     */
    public void updateUmbrellaHardwareUmbrellaStatus(String chipNumber,Integer status,String machineCode){
        try {
            UmbrellaHardwareUmbrella  umbrella = baseSelectUmbrellaHardwareUmbrellaNoCache(chipNumber);
            if(umbrella!= null) {
                UmbrellaHardwareUmbrella updateUmbrella = new UmbrellaHardwareUmbrella();
                //状态
                updateUmbrella.setUstatus(status);

                if(StringUtils.isNotBlank(machineCode)){//伞机码不为空更新，为空不更新，保留上一次的机器码
                    updateUmbrella.setCurrentMachineCode(machineCode);
                }

                //借出时，更新租用次数、最近一次租出
                if (UmbrellaConstant.UM_UMBRELLA_STATUS_3 == status) {
                    updateUmbrella.setRentingCount(umbrella.getRentingCount() + 1);
                    updateUmbrella.setLastRentalTime(DateUtil.getNowDate());
                }
                UmbrellaHardwareUmbrellaExample updateExample = new UmbrellaHardwareUmbrellaExample();
                updateExample.createCriteria().andChipNumberEqualTo(chipNumber);
                int ret = umbrellaHardwareUmbrellaService.updateByExampleSelective(updateUmbrella, updateExample);
            }
        }catch(Exception e){
            LOGGER.error("更新失败",e.getCause());
        }
    }
    /**
     * 更新用户借伞状态
     * @param userId
     * @param count
     * @return
     */
    public void updateUserAccountUmbrellaStatus(Integer userId, Integer count){
        try {
            WechatMpSystemAccount wechatMpSystemAccount =baseSelectWechatMpSystemAccont(userId);
            WechatMpSystemAccount updateAccount = new WechatMpSystemAccount();
            int number = wechatMpSystemAccount.getUmbrellanumber() + count;
            if(number<0){number = 0 ;}
            updateAccount.setUmbrellanumber(number);
            WechatMpSystemAccountExample updateExample = new WechatMpSystemAccountExample();
            updateExample.createCriteria().andUserIdEqualTo(userId);
            int ret = wechatMpSystemAccountService.updateByExampleSelective(updateAccount,updateExample);
        }catch(Exception e){
            LOGGER.error("更新失败",e.getCause());
        }
    }
    /**
     * 根据商户Id查询商户信息
     * @param mchId
     * @return
     */
    public PayMchInfo baseSelectPayMchInfoByMchId(String mchId){
        PayMchInfoExample mchInfoExample = new PayMchInfoExample();
        mchInfoExample.createCriteria().andMchidEqualTo(mchId);
        PayMchInfo payMchInfo = payMchInfoService.selectFirstByExample(mchInfoExample);
        return payMchInfo;
    }
    /**
     * 根据公号Id查询商户信息
     * @param jwid
     * @return
     */
    public PayMchInfo baseSelectPayMchInfoByJwid(String jwid){
        PayMchInfoExample mchInfoExample = new PayMchInfoExample();
        mchInfoExample.createCriteria().andMchidEqualTo(baseSelectPayMchIdByJwid(jwid));
        PayMchInfo payMchInfo = payMchInfoService.selectFirstByExample(mchInfoExample);
        return payMchInfo;
    }
    /**
     * 根据公号Id查询商户
     * @param jwid
     * @return
     */
    public String baseSelectPayMchIdByJwid(String jwid){
        WechatMpWebJwidExample wechatMpWebJwidExample = new WechatMpWebJwidExample();
        wechatMpWebJwidExample.createCriteria().andJwidEqualTo(jwid);
        WechatMpWebJwid wechatMpWebJwid = wechatMpWebJwidService.selectFirstByExample(wechatMpWebJwidExample);
        if(wechatMpWebJwid!=null){
            return wechatMpWebJwid.getMchid();
        }
        return mchId;
    }
    /**
     * 根据公号Id查询公号配置
     * @param jwid
     * @return
     */
    public WechatMpWebJwid baseSelectWechatMpWebJwidByJwid(String jwid){
        WechatMpWebJwidExample wechatMpWebJwidExample = new WechatMpWebJwidExample();
        wechatMpWebJwidExample.createCriteria().andJwidEqualTo(jwid);
        WechatMpWebJwid wechatMpWebJwid = wechatMpWebJwidService.selectFirstByExample(wechatMpWebJwidExample);
        return wechatMpWebJwid;
    }
    /**
     * 记录指令通信消息日志
     * @param reqMsg
     * @param resMsg
     * @return
     */
    @Async("threadPoolTaskExecutor")
    public void recordUmbrellaHardwareMqttcommandLog(Date beginTime,String reqMsg, Date endTime,String resMsg){
        boolean recordSwitch = false;
        boolean recordHeartBeatSwitch = false;
        String reqcommand = null;
        String reqmachineCode = null;
        int reqcode = 0;
        String reqmessage = null;
        String reqData = null;
        String rescommand = null;
        String resmachineCode = null;
        int rescode = 0;
        String resmessage = null;
        String resData = null;
        try {
            recordSwitch = Boolean.valueOf(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_COMMAND_LOG_SWITCH"));
            recordHeartBeatSwitch = Boolean.valueOf(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_COMMAND_LOG_HEARTBEAT_SWITCH"));
            if(recordSwitch) {
                try {
                    JSONObject jsonReqMsg = JsonUtil.getJSONObjectFromJson(reqMsg);
                    if(jsonReqMsg!=null) {
                        reqcommand = JsonUtil.getString(jsonReqMsg, "command");
                        reqmachineCode = JsonUtil.getString(jsonReqMsg, "machineCode");
                        reqcode = JsonUtil.getInteger(jsonReqMsg, "code");
                        reqmessage = JsonUtil.getString(jsonReqMsg, "message");
                        reqData = reqMsg;//JsonUtil.object2Json(jsonReqMsg.get("data"));
                    }
                } catch (Exception e) {
                }
                try {
                    JSONObject jsonResMsg = JsonUtil.getJSONObjectFromJson(resMsg);
                    if(jsonResMsg!=null) {
                        rescommand = JsonUtil.getString(jsonResMsg, "command");
                        resmachineCode = JsonUtil.getString(jsonResMsg, "machineCode");
                        rescode = JsonUtil.getInteger(jsonResMsg, "code");
                        resmessage = JsonUtil.getString(jsonResMsg, "message");
                        resData = resMsg;//JsonUtil.object2Json(jsonResMsg.get("data"));
                    }
                } catch (Exception e) {
                }
            }
        }catch(Exception e){
            LOGGER.error("解析通信消息日志失败",e);
        }finally {
            //记录日志
            if(recordSwitch) {
                try {
                    if((!reqcommand.equals(ApiConstant.UMBRELLA_MACHINE_COMMAND_20998) && !reqcommand.equals(ApiConstant.UMBRELLA_MACHINE_COMMAND_10998)) ||
                            ((reqcommand.equals(ApiConstant.UMBRELLA_MACHINE_COMMAND_20998) || reqcommand.equals(ApiConstant.UMBRELLA_MACHINE_COMMAND_10998)) && recordHeartBeatSwitch )
                    ){
                        UmbrellaHardwareMqttcommandLog newLog = new UmbrellaHardwareMqttcommandLog();
                        newLog.setReqCommand(reqcommand);
                        newLog.setReqMachineCode(reqmachineCode);
                        newLog.setReqTime(beginTime);
                        newLog.setReqCode(reqcode);
                        newLog.setReqMessage(reqmessage);
                        newLog.setReqData(reqData);
                        newLog.setResCommand(rescommand);
                        newLog.setResMachineCode(resmachineCode);
                        newLog.setResTime(endTime);
                        newLog.setResCode(rescode);
                        newLog.setResMessage(resmessage);
                        newLog.setResData(resData);
                        int ret = umbrellaHardwareMqttcommandLogService.insert(newLog);
                    }
                } catch (Exception e) {
                    LOGGER.error("写入通信消息日志失败", e);
                }
            }
        }
    }

    /**
     * 根据代理Id和配置项查询个性规则配置
     * @param agentId
     * @param  code
     * @return
     */
    public UmbrellaRuleSpecialconfigDetail baseSelectAgentSpecialConfig(Integer agentId, String code){
        UmbrellaRuleSpecialconfigDetailExample umbrellaRuleSpecialconfigDetailExample = new UmbrellaRuleSpecialconfigDetailExample();
        UmbrellaRuleSpecialconfigDetailExample.Criteria detailCriteria = umbrellaRuleSpecialconfigDetailExample.createCriteria();
        detailCriteria.andAgentIdEqualTo(agentId);
        detailCriteria.andCodeEqualTo(code);
        UmbrellaRuleSpecialconfigDetail detail = umbrellaRuleSpecialconfigDetailService.selectFirstByExample(umbrellaRuleSpecialconfigDetailExample);
        return detail;
    }
    /**
     * 根据用户查询有效的fromId
     * @param userId
     * @return
     */
    public WechatMpWxappfrommessage baseSelectWechatMpWxappfromIdByUserId(Integer userId){
        WechatMpWxappfrommessageExample wechatMpWxappfrommessageExample = new WechatMpWxappfrommessageExample();
        //查询表单提交的formid
        WechatMpWxappfrommessageExample.Criteria criteria = wechatMpWxappfrommessageExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andStatusEqualTo(Constant.CONST_ENABLE);
        criteria.andEndTimeGreaterThan(DateUtil.getDate());
        criteria.andFormidtypeEqualTo(0);
        criteria.andUsetimesEqualTo(0);
        //或者查询支付的prepay_id
        WechatMpWxappfrommessageExample.Criteria criteria2 = wechatMpWxappfrommessageExample.createCriteria();
        criteria2.andUserIdEqualTo(userId);
        criteria2.andStatusEqualTo(Constant.CONST_ENABLE);
        criteria2.andEndTimeGreaterThan(DateUtil.getDate());
        criteria2.andFormidtypeEqualTo(1);
        criteria2.andUsetimesLessThan(3);
        WechatMpWxappfrommessage formMessage = wechatMpWxappfrommessageService.selectFirstByExample(wechatMpWxappfrommessageExample);
        return formMessage;
    }
    /**
     * 插入用户fromId
     * @param userId
     * @param formId
     * @return
     */
    public int insertWechatMpWxappfromIdByUserId(Integer userId,String formId,Integer formIdType,Integer totalTimes){
        WechatMpWxappfrommessage wechatMpWxappfrommessage = new WechatMpWxappfrommessage();
        wechatMpWxappfrommessage.setUserId(userId);
        Date ctime = DateUtil.getDate();
        wechatMpWxappfrommessage.setCreateTime(ctime);
        Calendar c = Calendar.getInstance();
        c.setTime(ctime);
        c.add(Calendar.DAY_OF_MONTH,7);
        wechatMpWxappfrommessage.setEndTime(c.getTime());
        wechatMpWxappfrommessage.setFormid(formId);
        wechatMpWxappfrommessage.setFormidtype(formIdType);
        wechatMpWxappfrommessage.setTotaltimes(totalTimes);
        wechatMpWxappfrommessage.setUsetimes(0);
        wechatMpWxappfrommessage.setStatus(Constant.CONST_ENABLE);
        return wechatMpWxappfrommessageService.insert(wechatMpWxappfrommessage);
    }
    /**
     * 更新用户fromId
     * @param userId
     * @return
     */
    public int updatetWechatMpWxappfromIdById(Integer id,Integer formIdType,Integer useTimes,String message){
        WechatMpWxappfrommessageExample wechatMpWxappfrommessageExample = new WechatMpWxappfrommessageExample();
        WechatMpWxappfrommessageExample.Criteria criteria = wechatMpWxappfrommessageExample.createCriteria();
        criteria.andIdEqualTo(id);
        WechatMpWxappfrommessage wechatMpWxappfrommessage = new WechatMpWxappfrommessage();
        wechatMpWxappfrommessage.setLastUseTime(DateUtil.getDate());
        int totalUseTimes = useTimes + 1;
        wechatMpWxappfrommessage.setUsetimes(totalUseTimes);
        if(formIdType == 0 || (formIdType == 1 && totalUseTimes >=3) ) {
            wechatMpWxappfrommessage.setStatus(Constant.CONST_DISABLE);
        }
        wechatMpWxappfrommessage.setRemark(message);
        return wechatMpWxappfrommessageService.updateByExampleSelective(wechatMpWxappfrommessage,wechatMpWxappfrommessageExample);
    }

    /**
     * 根据公号和类型查询模板Id
     * @param jwid
     * @param templateType
     * @return
     */
    public WechatMpWxapptempletecfg baseSelectWechatMpWxapptempletecfgByJwidAndType(String jwid,String templateType){
        WechatMpWxapptempletecfgExample wechatMpWxapptempletecfgExample = new WechatMpWxapptempletecfgExample();
        //查询条件
        WechatMpWxapptempletecfgExample.Criteria criteria = wechatMpWxapptempletecfgExample.createCriteria();
        criteria.andJwidEqualTo(jwid);
        criteria.andTemplatetypeEqualTo(templateType);
        WechatMpWxapptempletecfg wechatMpWxapptempletecfg = wechatMpWxapptempletecfgService.selectFirstByExample(wechatMpWxapptempletecfgExample);
        return wechatMpWxapptempletecfg;
    }
    /**
     * 计算费用
     * @param userId
     * @return
     */
    public double calculateOrderCost(BusinessOrderUmbrellaConsumption consumption,UmbrellaRuleRent rent){
        double cost = 0;
        //未完成订单
        if(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_6 != consumption.getStatus()){
            //查询用户账号
            boolean isDifference = false;
            try{
                isDifference = "true".equals(upmsSystemParamService.querySystemParamValueByParam_key("BUSINESS_ORDER_TIMECARD_SETTLE_DIFF_AGENT"));
            }catch(Exception e){}
            BusinessOrderUmbrellaTimecard latestTimeCard =  this.baseSelectLastBusinessOrderUmbrellaTimecardNoCache(consumption.getUserid(),consumption.getAgentid(),isDifference);
            DecimalFormat df = new DecimalFormat("0.00");
            Date nowDate = new Date();
            //已购买时长卡还没到期
            if(latestTimeCard!=null && latestTimeCard.getCardAfterEndtime()!=null && latestTimeCard.getCardAfterEndtime().after(nowDate)){
                cost = 0;
            }else {
                cost = MoneyUtil.getCostBetweenTime(consumption.getBegintime(), nowDate, rent.getPrice().doubleValue(), rent.getChargelength(), rent.getChargetype(),
                        rent.getFreetimelength(), rent.getFreetimetype());
                //增加封顶金额计算租金
                if(cost>consumption.getLimitamount().doubleValue() && consumption.getLimitamount().doubleValue()>0){
                    cost = consumption.getLimitamount().doubleValue();
                }
            }
        //已完成订单
        }else{
            cost = consumption.getPayamount().doubleValue();
        }
        return cost;
    }

}
